//
//  SinaTabBar.swift
//  mySina
//
//  Created by 刘莹 on 2016/11/12.
//  Copyright © 2016年 liuying. All rights reserved.
//

import UIKit

class SinaTabBar: UITabBar {
    //a.定义闭包
    var composeClosure: (() -> ())?
    
    
    //MARK: -
    //MARK: - 重写init&添加➕按钮&监听点击事件
    override init(frame:CGRect){
    
        super.init(frame: frame)
        self.addSubview(composeBtn)
        self.composeBtn.addTarget(self, action: #selector(composeClick), for: .touchUpInside)
    }
    //MARK: -
    //MARK: - 监听➕按钮点击事件
    func composeClick(){
        
        composeClosure?()
        
    }
    //MARK: -
    //MARK: - 解档方法
    /*
     1.默认通过xib加载就会报错
     2.改写为支持手写和xib创建
     */
    required init?(coder aDecoder: NSCoder) {
        //实现报错
        //fatalError("init(coder:) has not been implemented")
        //支持手写和xib
        super.init(coder: aDecoder)
        self.addSubview(composeBtn)
        
        
    }
    //MARK: -
    //MARK: - 加载xib
    override func awakeFromNib() {
        
        //如果是手写代码不会调用次方法
    }
    
    //MARK: -
    //MARK: - 懒加载➕按钮
    lazy var composeBtn: UIButton = {
    
        let btn = UIButton()
        //设置图片
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
    
    return btn
    }()
    //MARK: -
    //MARK: - 修改内部视图的位置,重写layoutsubViews
    override func layoutSubviews()
        {
            //1.调用父类方法
            super.layoutSubviews()
            //2.获取UITabBarButton类型的控件,并修改frame
            let  w = UIScreen.main.bounds.width/5
            let h = self.bounds.height
            var index = 0
            for i in subviews{
            
                    //判断类型
                if i.isKind(of: NSClassFromString("UITabBarButton")!) {
                    
                    i.frame = CGRect(x: CGFloat(index)*w, y: 0, width: w, height: h)
                    if index == 1 {
                        index += 1
                    }
                    index+=1
                }
            }
        //设置➕按钮的frame
            composeBtn.bounds.size = CGSize(width: w, height: h)
            composeBtn.center = CGPoint(x: self.center.x, y: h*0.5)
            
            composeBtn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
            composeBtn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
            
        }
    

}
